package com.vertx.future;

import com.vertx.util.Runner;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.ext.web.client.WebClient;

public class FutureVerticle extends AbstractVerticle {

	public static void main(String[] args) {
		Runner.runExample(FutureVerticle.class);
	}

	public void start(Promise<Void> startPromise) throws Exception {

		Future future1 = call1();
		Future future2 = call2();


		CompositeFuture.all(future1, future2).onSuccess(res -> {
			System.out.println("res.resultAt(1) = " + res.resultAt(1).toString());
			System.out.println("all finish");
		});

//    CompositeFuture.any(future2, future1).onSuccess(res -> {
//      //System.out.println("res.resultAt(0) = " +  res.resultAt(0).toString());
//      System.out.println("all finish");
//    });
	}

	protected Future<String> call1() {
		Promise<String> future = Promise.promise();
		WebClient client = WebClient.create(vertx);
		client.get(8080, "localhost", "/sleep1/walter-sleep1/123")
				.send()
				.onSuccess(response -> {
					future.complete(response.bodyAsString());
				})
				.onFailure(err -> {
					System.out.println("fail:" + err.getMessage());
				});

		return future.future();
	}

	protected Future<String> call2() {
		Promise<String> promise = Promise.promise();
		WebClient client = WebClient.create(vertx);
		client.get(8081, "localhost", "/sleep2/walter-sleep2/455")
				.send()
				.onSuccess(response -> {
					promise.complete(response.bodyAsString());
				})
				.onFailure(err -> {
					System.out.println("fail:" + err.getMessage());
				});

		return promise.future();
	}

}
